package com.abiao.shop.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @Description: MQConfig   消息队列配置(学习记录，与项目无关)
 * @Author: AB
 * @Date: 2021-07-21
 * @Version:v1.0
 */
@Configuration
public class MQConfig {
    public static final String QUEUE_NAME = "queue";
    public static final String QUEUE_1 = "Queue1";
    public static final String QUEUE_2 = "Queue2";
    public static final String HEADER_QUEUE = "headerQueue";
    public static final String TOPIC_EXCHANGE = "topicExchange";
    public static final String FANOUT_EXCHANGE = "fanoutExchange";
    public static final String HEADER_EXCHANGE = "headerExchange";
    /**
     *  Exchange：direct模式,不采用路由交换机，直接发送到队列中
     */
    @Bean
    public Queue queue(){
        //队列名 "queue" ,持久化 true
        return new Queue(QUEUE_NAME,true);
    }
    @Bean
    public Queue Queue1(){
        return new Queue(QUEUE_1,true);
    }
    @Bean
    public Queue Queue2(){
        return new Queue(QUEUE_2,true);
    }

    /**
     * Exchange：topic模式,根据key指定队列发送，key可使用通配符（*表示一个字符，#表示0到多个字符）
     */
//    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(TOPIC_EXCHANGE);
    }
    @Bean
    public Binding topicQ1Bind(){
        return BindingBuilder.bind(Queue1()).to(topicExchange()).with("topic.key1");
    }
    @Bean
    public Binding topicQ2Bind(){
        return BindingBuilder.bind(Queue2()).to(topicExchange()).with("topic.#");
    }

    /**
     * Exchange：fanout模式,广播发送，交换机中所有队列均能收到
     */
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(FANOUT_EXCHANGE);
    }
    @Bean
    public Binding fanoutBindQ1(){
        return BindingBuilder.bind(Queue1()).to(fanoutExchange());
    }
    @Bean
    public Binding fanoutBindQ2(){
        return BindingBuilder.bind(Queue2()).to(fanoutExchange());
    }

    /**
     * Exchange：Header模式,发送的消息类型为Message对象，
     * 根据Message对象的Header匹配队列发送，绑定队列时指定Header（key-value）
     * 可以设置header匹配模式
     */
    @Bean
    public Queue headerQueue(){
        return new Queue(HEADER_QUEUE,true);
    }
    @Bean
    public HeadersExchange headersExchange(){
        return new HeadersExchange(HEADER_EXCHANGE);
    }
    @Bean
    public Binding headerExchangeBind(){
        Map<String,Object> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");
        return BindingBuilder.bind(headerQueue()).to(headersExchange()).whereAll(map).match();
    }
}
